package cn.ito.zjgsu.utils.impl;

import java.io.InputStream;
import java.io.PushbackInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import cn.ito.zjgsu.utils.ExcelReader;

@Component
public class ExcelReaderUtil implements ExcelReader {

	private POIFSFileSystem fs;
	private HSSFWorkbook wb;
	private HSSFSheet sheet;
	private HSSFRow row;

	private XSSFWorkbook xwb;
	private XSSFSheet xsheet;
	private XSSFRow xrow;

	@Override
	public Map<Integer, String[]> readExcelContent(String name, InputStream in) {
		try{
		if (!in.markSupported()) {
			in = new PushbackInputStream(in, 8);
		}
		if (POIFSFileSystem.hasPOIFSHeader(in)) {
			return readExcelContent(in);
		}
		if (POIXMLDocument.hasOOXMLHeader(in)) {
			return readExcelContent2007(OPCPackage.open(in));
		}
		throw new IllegalArgumentException("你的excel版本目前poi解析不了");
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
//		String end = name.substring(name.lastIndexOf('.') + 1);
//		if (end.equals("xls"))
//			return readExcelContent(is);
//		else
//			return readExcelContent2007(is);
	}

	public Map<Integer, String[]> readExcelContent(InputStream is) {
		Map<Integer, String[]> content = new HashMap<Integer, String[]>();
		String str = "";
		try {
			fs = new POIFSFileSystem(is);
			wb = new HSSFWorkbook(fs);
		} catch (Exception e) {

			throw new RuntimeException(e);
		}
		sheet = wb.getSheetAt(0);

		int rowNum = sheet.getLastRowNum();
		if (rowNum < 1)
			throw new RuntimeException("模板错误");
		row = sheet.getRow(0);
		int colNum = row.getPhysicalNumberOfCells();
		// if(colNum<4) throw new RuntimeException("模板错误");
		for (int i = 0; i <= rowNum; i++) {
			String[] temp = new String[colNum];
			row = sheet.getRow(i);
			int j = 0;
			while (j < colNum) {

				str = getCellFormatValue(row.getCell(j)).trim();
				temp[j] = str;
				j++;
			}
			content.put(i, temp);
			str = "";
		}
		return content;

	}

	public Map<Integer, String[]> readExcelContent2007(OPCPackage opcPackage) {

		Map<Integer, String[]> content = new HashMap<Integer, String[]>();
		String str = "";
		try {
			xwb = new XSSFWorkbook(opcPackage);
		} catch (Exception e) {
			throw new RuntimeException(e);

		}
		xsheet = xwb.getSheetAt(0);

		int rowNum = xsheet.getLastRowNum();
		if (rowNum < 1)
			throw new RuntimeException("模板错误,该模板数据行数为" + rowNum);
		xrow = xsheet.getRow(0);
		int colNum = xrow.getPhysicalNumberOfCells();
		// if(colNum<4) throw new RuntimeException("模板错误");
		for (int i = 0; i <= rowNum; i++) {
			String[] temp = new String[colNum];
			xrow = xsheet.getRow(i);
			int j = 0;
			while (j < colNum) {

				str = getCellFormatValue(xrow.getCell((short) j)).trim();
				temp[j] = str;
				j++;
			}
			content.put(i, temp);
			str = "";
		}
		return content;

	}

	private String getCellFormatValue(HSSFCell cell) {
		String cellvalue = "";
		if (cell != null) {
			switch (cell.getCellType()) {
			case HSSFCell.CELL_TYPE_NUMERIC:
				cellvalue = Double.toString(cell.getNumericCellValue());
				if (cellvalue.indexOf(".") > 0) {

					cellvalue = cellvalue.replaceAll("0+?$", "");
					cellvalue = cellvalue.replaceAll("[.]$", "");
				}
				break;
			case HSSFCell.CELL_TYPE_FORMULA: {
				if (HSSFDateUtil.isCellDateFormatted(cell)) {
					Date date = cell.getDateCellValue();
					SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
					cellvalue = sdf.format(date);
				} else {
					cellvalue = String.valueOf(cell.getNumericCellValue());
				}
				break;
			}
			case HSSFCell.CELL_TYPE_STRING:
				cellvalue = cell.getRichStringCellValue().getString();
				break;
			default:
				cellvalue = " ";
			}
		} else {
			cellvalue = "";
		}
		return cellvalue;

	}

	private String getCellFormatValue(XSSFCell cell) {
		String cellvalue = "";
		if (cell != null) {
			switch (cell.getCellType()) {
			case HSSFCell.CELL_TYPE_NUMERIC:
				cellvalue = Double.toString(cell.getNumericCellValue());
				if (cellvalue.indexOf(".") > 0) {

					cellvalue = cellvalue.replaceAll("0+?$", "");
					cellvalue = cellvalue.replaceAll("[.]$", "");
				}
				break;
			case HSSFCell.CELL_TYPE_FORMULA: {
				if (HSSFDateUtil.isCellDateFormatted(cell)) {
					Date date = cell.getDateCellValue();
					SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
					cellvalue = sdf.format(date);
				} else {
					cellvalue = String.valueOf(cell.getNumericCellValue());
				}
				break;
			}
			case HSSFCell.CELL_TYPE_STRING:
				cellvalue = cell.getRichStringCellValue().getString();
				break;
			default:
				cellvalue = "";
			}
		} else {
			cellvalue = "";
		}
		return cellvalue;

	}

}